<template>
    <div class="container">
        <!-- 顶部信息栏 -->
        <div class="top-info">
            <div class="time">{{ time }}</div>
            <div class="bmi-info">
                <div class="bmi-value">BMI {{ bmi }}</div>
                <div class="weight">
                    {{ weight }}kg <span v-if="weightStatus === '偏高'">(偏高)</span>
                </div>
                <van-button @click="showDialog" class="record-btn" type="primary">记录体重</van-button>
            </div>
        </div>
        <!-- 体重趋势图 -->
        <div class="weight-trend">
            <div class="trend-title">体重趋势(单位:kg)</div>
            <div id="weight-chart"></div>
        </div>
        <!-- 体重记录列表 -->
        <div class="weight-record">
            <div class="record-title">体重记录</div>
            <van-list>
                <van-cell-group v-for="(record, index) in records" :key="index">
                    <van-cell :title="`${record.monthDay}\n${record.year}`" :value="`${record.weight}kg`">
                        <template #right-icon>
                            <van-tag type="success" v-if="record.status === '正常'">正常</van-tag>
                            <!-- <van-icon name="edit" size="16" color="#1989fa" />
                            <van-icon name="delete" size="16" color="#1989fa" /> -->
                        </template>
                    </van-cell>
                </van-cell-group>
            </van-list>
        </div>
    </div>
    <!-- 底部弹出层 -->
    <van-popup v-model:show="showBottom" position="bottom" round :style="{ height: '40%' }">
        <div class="popup-content">
            <h3 class="popup-title">记录体重</h3>
            <van-form @submit="onSubmit">
                <van-cell-group inset>
                    <van-field v-model="inputWeight" label="体重" placeholder="请输入体重(kg)" type="number"
                        :rules="[{ required: true, message: '请填写体重' }]" />
                </van-cell-group>
                <div style="margin: 16px">
                    <van-button round block type="primary" native-type="submit">
                        确认提交
                    </van-button>
                </div>
            </van-form>
        </div>
    </van-popup>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import * as echarts from 'echarts';
import { Dialog } from 'vant';
import { showConfirmDialog } from 'vant';
import axios from 'axios';

// 定义响应式数据
const time = ref('');
const bmi = ref(0);
const weight = ref(0);
const weightStatus = computed(() => (weight.value > 70 ? '偏高' : ''));
const records = ref([]);
const weightData = ref([]);
const xAxisData = ref([]);
const showBottom = ref(false);
const inputWeight = ref('');
import { useCounterStore } from '@/stores/counter';

const store = useCounterStore();
// 实时查询数据方法
const fetchData = async () => {
    try {
        const response = await axios.get('http://localhost:5223/api/HealthMonitoring/GetBMI', {
            params: {
                UserId: store.useStore.mId
            }
        });
        if (response.data.code === 210) {
            const dataList = response.data.data;
            if (dataList.length > 0) {
                bmi.value = dataList[0].bmi;
            }
            records.value = dataList.map(item => {
                const dateObj = new Date(item.createTime);
                const month = dateObj.getMonth() + 1;
                const day = dateObj.getDate();
                const year = dateObj.getFullYear();
                return {
                    date: item.createTime,
                    weight: item.weight,
                    status: item.weight > 70 ? '偏高' : '正常',
                    monthDay: `${month}/${day}`,
                    year: year
                };
            });
            weightData.value = records.value.map(item => item.weight);
            xAxisData.value = records.value.map(item => item.monthDay);

            const chartDom = document.getElementById('weight-chart');
            const myChart = echarts.init(chartDom);
            const option = {
                xAxis: {
                    data: xAxisData.value
                },
                yAxis: {},
                series: [
                    {
                        data: weightData.value,
                        type: 'line',
                        areaStyle: {}
                    }
                ]
            };
            myChart.setOption(option);

            // 监听窗口大小变化，自适应调整图表大小
            window.addEventListener('resize', () => {
                myChart.resize();
            });

            // 假设从数据中获取最新的体重和时间
            const latestRecord = records.value[records.value.length - 1];
            weight.value = latestRecord?.weight || 0;
            time.value = latestRecord?.date || '';
        } else {
            console.error('数据获取失败，错误信息:', response.data.msg);
        }
    } catch (error) {
        console.error('数据获取失败', error);
    }
};

onMounted(() => {
    fetchData();
});

const showDialog = () => {
    showBottom.value = true;
    inputWeight.value = ''; // 每次打开清空输入
};

const onSubmit = async () => {
    if (!inputWeight.value) return;

    // 更新当前体重
    weight.value = parseFloat(inputWeight.value);

    // 添加新记录
    const newDate = new Date();
    const month = newDate.getMonth() + 1;
    const day = newDate.getDate();
    const year = newDate.getFullYear();
    records.value.unshift({
        date: newDate.toISOString(),
        weight: weight.value,
        status: weight.value > 70 ? '偏高' : '正常',
        monthDay: `${month}/${day}`,
        year: year
    });

    // 关闭弹窗
    showBottom.value = false;

    // 调用添加 BMI 数据的接口
    try {
        const response = await axios.post('http://localhost:5260/api/HealthMonitoringControllers/AddBMI', {
            UserId: store.useStore.mId,
            UserName: store.useStore.userName,
            Higher: 170,
            Weight: weight.value,
            BMI: bmi.value,
            CreateTime: newDate
        });
        console.log('数据添加成功', response.data);
        // 再次调用查询接口获取最新数据
        await fetchData();
    } catch (error) {
        console.error('数据添加失败', error);
    }

    // 更新体重趋势图的数据
    weightData.value.unshift(weight.value);
    xAxisData.value.unshift(`${month}/${day}`);

    const chartDom = document.getElementById('weight-chart');
    const myChart = echarts.getInstanceByDom(chartDom);
    const option = {
        xAxis: {
            data: xAxisData.value
        },
        yAxis: {},
        series: [
            {
                data: weightData.value,
                type: 'line',
                areaStyle: {}
            }
        ]
    };
    myChart.setOption(option);
};

const updateChart = (newWeight) => {
    // 示例：添加最新数据点
    weightData.value.push(newWeight);
    const newDate = new Date();
    const month = newDate.getMonth() + 1;
    const day = newDate.getDate();
    xAxisData.value.push(`${month}/${day}`);

    // 重新渲染图表
    const chartDom = document.getElementById('weight-chart');
    const myChart = echarts.getInstanceByDom(chartDom);
    myChart.setOption({
        xAxis: {
            data: xAxisData.value
        },
        series: [
            {
                data: weightData.value
            }
        ]
    });
};
</script>
<style scoped>
.container {
    padding: 16px;
    background-color: #f5f5f5;
}

.top-info {
    display: flex;
    flex-direction: column;
    /* 改为垂直排列 */
    align-items: center;
    background-color: #409eff;
    color: white;
    padding: 20px;
    border-radius: 8px;
}

.time {
    font-size: 14px;
}

.bmi-info {
    text-align: center;
}

.bmi-value {
    font-size: 36px;
    font-weight: bold;
    margin-bottom: 8px;
}

.weight {
    font-size: 14px;
    color: #f56c6c;
}

.record-btn {
    margin-top: 10px;
}

.weight-trend {
    margin-top: 20px;
    background-color: white;
    padding: 20px;
    border-radius: 8px;
}

.trend-title {
    font-size: 16px;
    margin-bottom: 10px;
}

.weight-record {
    margin-top: 20px;
    background-color: white;
    border-radius: 8px;
}

.record-title {
    font-size: 16px;
    padding: 10px;
    border-bottom: 1px solid #ebeef5;
}

/* 设置图表容器样式 */
#weight-chart {
    height: 200px;
    width: 100%;
    /* 确保图表宽度自适应容器 */
}

/* 新增底部弹窗样式 */
.popup-content {
    padding: 20px;
}

.popup-title {
    text-align: center;
    margin-bottom: 20px;
    color: #333;
}

.van-field {
    margin: 15px 0;
}
</style>
